<template>
  <div class="ui-upload-box" v-if="!imageUrl">
    <el-upload
      class="avatar-uploader"
      accept="video/mp4,video/webm"
      :show-file-list="false"
      :on-change="handleAvatarSuccess"
      :on-error="handleAvatarError"
      :before-upload="beforeUpload"
      :style="{
        width: videoStyle.width + 'px',
        height: videoStyle.height + 'px'
      }"
    >
      <el-icon class="avatar-uploader-icon">
        <icon-video-two />
      </el-icon>
      <template #tip>
        <div class="el-upload__tip">Please upload a video in MP4 format</div>
      </template>
    </el-upload>
    <el-progress
      striped-flow
      striped
      :percentage="percentage"
      v-if="percentage"
    />
  </div>
  <div v-else class="text-left" style="display: flex">
    <div
      class="prism-player"
      id="J_prismPlayer"
      :style="{
        width: playVideoStyle.width + 'px',
        height: playVideoStyle.height + 'px',
        display: 'inline-block'
      }"
    ></div>
    <div style="display: flex; align-items: flex-end">
      <el-button
        type="primary"
        style="font-size: 12px; margin-left: 22px"
        @click="reselectFn"
        >重新选择</el-button
      >
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, toRefs, defineExpose, watch, defineProps } from "vue";
import { ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import service from "@/utils/system/request";
import md5 from "js-md5";
import OSS from "ali-oss";
import { useStore } from "vuex";
import { closeLoading, showLoading } from "@/utils/common";

const props = defineProps(["videoUrl", "videoStyle", "playVideoStyle"]);
const emit = defineEmits(["aliyunUpload"]);
const videoUrl = ref();
const videoStyle = props.videoStyle;
const playVideoStyle = props.playVideoStyle;
// const props = defineProps({
//   videoUrl:{
//     type: String,
//     default: ''
//   },
//   videoStyle:{ // 上传样式
//     type:Object,
//     default: () => { return {width:'140',height:'85',lineHeight:'90'}}
//   },
//   playVideoStyle: { // 播放样式
//     type:Object,
//     default: () => { return {width:'400',height:'225'}}
//   }
// })
watch(
  () => props.videoUrl,
  newVal => {
    console.log(newVal, "[[[");
    videoUrl.value = newVal;

    getStatus();
  },
  { deep: true }
);

const store = useStore();

const reselectFn = () => {
  imageUrl.value = "";
  percentage.value = 0;
  emit("aliyunUpload", imageUrl.value);
};

const dialogImageUrl = ref(""); // 预览图url
const dialogVisible = ref(false); // 预览弹窗
const imageUrl = ref("");
const handleAvatarSuccess = (response, uploadFile) => {};
const handleAvatarError = error => {
  console.log(error, "error");
};
// 上传前准备
const beforeUpload = file => {
  setTimeout(() => {
    getTime(file);
  }, 100);
  return false;
};

const host = ref("");
const ossConfig = ref("");
const getTime = async file => {
  // 判断上传凭证是否过期
  // console.log(store.state.user)
  // debugger
  // host.value = store.state.user.host
  // ossConfig.value = store.state.user.ossConfig
  // let time2 = Math.round(new Date().getTime() / 1000)
  // if (time2 > ossConfig.value.expire) {
  getSignature(file);
  // } else {
  //   upload(file)
  // }
};
const getSignature = file => {
  const self = this;
  service.get(`admin/upload/signature`).then(({ code, data }) => {
    if (code === 0) {
      host.value = data.host;
      ossConfig.value = data;
      upload(file);
    }
  });
};
const newGuid = () => {
  function S4() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
  }

  return S4() + S4() + S4() + S4() + S4() + S4() + S4() + S4();
};
const getExtension = file => {
  if (file) {
    // 通过正则表达式提取文件后缀名
    const regex = /(?:\.([^.]+))?$/;
    const result = regex.exec(file.name);
    return result?.[1] || null;
  }
  return null; // 处理输入为 null 的情况
};

const upload = async file => {
  console.log(file, "file");

  showLoading("Uploading");
  const fileGuid = newGuid();
  const fileSuffix = getExtension(file);
  const newFileName = `${ossConfig.value.dir}${fileGuid}.${fileSuffix}`;
  console.log(newFileName, "newFileName");
  var clients = await new OSS({
    // region: 'cn-shanghai', //阿里云oss地区
    region: ossConfig.value.endpoint.split(".")[0], //阿里云oss地区
    accessKeyId: ossConfig.value.access_id, //id
    secure: true,
    accessKeySecret: ossConfig.value.secret, //密钥
    bucket: ossConfig.value.bucket //远程仓库名称
  }).multipartUpload(newFileName, file, {
    parallel: 5,
    partSize: 1048576,
    timeout: 120000, //设置超时时间
    progress,
    headers: {
      "Content-Type": "video/mp4"
    }
  });
  console.log(clients, "clients====");
  const parts = clients.res.requestUrls[0].split("?");
  if (parts.length > 1) {
    imageUrl.value = parts[0];
    // insertFn(cleanedString)
  } else {
    imageUrl.value = clients.res.requestUrls[0];
  }
  closeLoading();
  setTimeout(() => {
    var player = new Aliplayer(
      {
        id: "J_prismPlayer",
        width: "100%",
        autoplay: false,
        source: imageUrl.value,
        showBarrage: false,
        skinLayout: [
          { name: "bigPlayButton", align: "blabs", x: 30, y: 80 },
          {
            name: "H5Loading",
            align: "cc"
          },
          { name: "errorDisplay", align: "tlabs", x: 0, y: 0 },
          { name: "infoDisplay" },
          { name: "tooltip", align: "blabs", x: 0, y: 56 },
          { name: "thumbnail" },
          {
            name: "controlBar",
            align: "blabs",
            x: 0,
            y: 0,
            children: [
              { name: "progress", align: "blabs", x: 0, y: 44 },
              { name: "playButton", align: "tl", x: 15, y: 12 },
              { name: "timeDisplay", align: "tl", x: 10, y: 7 },
              { name: "fullScreenButton", align: "tr", x: 10, y: 12 },

              { name: "setting", align: "tr", x: 15, y: 12 },
              { name: "volume", align: "tr", x: 5, y: 10 }
            ]
          }
        ]
      },
      function (player) {
        console.log("播放器创建好了。");
      }
    );
  }, 300);
  emit("aliyunUpload", imageUrl.value);
  console.log(imageUrl.value, "imageUrl.value----");
};
const percentage = ref(0);
const checkpoints = ref();
//上传进度
const progress = (progress, checkpoint) => {
  // Object的上传进度。
  console.log("上传进度", progress);
  percentage.value = Number((progress * 100).toFixed(0));
  // 分片上传的断点信息。
  console.log("分片上传的断点信息", checkpoint);
  if (checkpoint && checkpoint.uploadId) {
    checkpoints[checkpoint.uploadId] = checkpoint;
    console.log("打印checkpoints", checkpoints);
  }
};
const clearPic = () => {
  imageUrl.value = "";
  videoUrl.value = "";
};
// 预览图片
const handlePictureCardPreview = file => {
  dialogImageUrl.value = file;
  dialogVisible.value = true;
};
const getStatus = () => {
  imageUrl.value = videoUrl.value;
  console.log(imageUrl.value, "---");
  if (imageUrl.value) {
    setTimeout(() => {
      var player = new Aliplayer(
        {
          id: "J_prismPlayer",
          width: "100%",
          autoplay: false,
          source: imageUrl.value,
          showBarrage: false,
          skinLayout: [
            { name: "bigPlayButton", align: "blabs", x: 30, y: 80 },
            {
              name: "H5Loading",
              align: "cc"
            },
            { name: "errorDisplay", align: "tlabs", x: 0, y: 0 },
            { name: "infoDisplay" },
            { name: "tooltip", align: "blabs", x: 0, y: 56 },
            { name: "thumbnail" },
            {
              name: "controlBar",
              align: "blabs",
              x: 0,
              y: 0,
              children: [
                { name: "progress", align: "blabs", x: 0, y: 44 },
                { name: "playButton", align: "tl", x: 15, y: 12 },
                { name: "timeDisplay", align: "tl", x: 10, y: 7 },
                { name: "fullScreenButton", align: "tr", x: 10, y: 12 },

                { name: "setting", align: "tr", x: 15, y: 12 },
                { name: "volume", align: "tr", x: 5, y: 10 }
              ]
            }
          ]
        },
        function (player) {
          console.log("播放器创建好了。");
        }
      );
    }, 300);
  }
};
defineExpose({
  clearPic
});
onMounted(() => {});
</script>

<style lang="scss" scoped>
@import "https://g.alicdn.com/de/prismplayer/2.7.4/skins/default/aliplayer-min.css";

.ui-image-box {
  margin: 0 auto;
  text-align: center;
  //width: 500px;
  height: auto;
}

.full_img {
  width: 100%;
  text-align: center;
}

.prism-player {
}

:deep(.avatar-uploader .avatar) {
  width: 120px;
  height: 120px;
  display: inline-block;
}

:deep(.el-upload__tip) {
  margin: 0;
  margin-top: -6px;
}

:deep(.el-icon.avatar-uploader-icon) {
  font-size: 28px;
  width: 120px;
  height: 120px;
  text-align: center;
  position: absolute;
  left: 0;
  line-height: 120px;
}

:deep(.avatar-uploader .el-upload) {
  border: 2px dashed #8c939d;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  width: 120px;
  height: 120px;
}

:deep(.avatar-uploader .el-upload:hover) {
  border-color: var(--el-color-primary);
  color: #7e9cff !important;

  .avatar-uploader-icon {
    color: #7e9cff !important;
  }
}

:deep(.avatar-uploader) {
  padding-top: 8px;
  width: 220px !important;
  height: 160px !important;
}

.demo-image__error .image-slot {
  font-size: 30px;
}

.demo-image__error .image-slot .el-icon {
  font-size: 30px;
}

.demo-image__error .el-image {
  width: 100%;
  background: red;
}

.previewImage {
  min-width: 120px;
  max-width: 220px;
  height: 120px;
  border-radius: 6px;
}
</style>
